package cn.work.control;

import cn.work.bean.servicebean;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.List;

import cn.work.service.goodsService;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.FileItem;

@WebServlet(name = "ServiceAddServlet", urlPatterns = "/ServiceAddServlet")

public class ServiceAddServlet extends HttpServlet {
    private goodsService gdao = new goodsService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }



    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String method = request.getParameter("method");
        System.out.println("你好");
        if ("save".equals(method)) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            servicebean ser = new servicebean();
            try {
                List<FileItem> items = upload.parseRequest(request);
                for (FileItem item : items) {
                    if (item.isFormField()) {
                        // 打印所有字段信息
                        System.out.println("字段名：" + item.getFieldName() + " 值：" + item.getString("UTF-8"));
                        switch (item.getFieldName()) {
                            case "name":
                                ser.setName(item.getString("UTF-8"));
                                break;
                            case "classname":
                                ser.setClassname(item.getString("UTF-8"));
                                break;
                            case "doctor":
                                ser.setDoctor(item.getString("UTF-8"));
                                break;
                            case "time":
                                ser.setTime(item.getString("UTF-8"));
                                break;
                            case "price":
                                ser.setPrice(Double.parseDouble(item.getString("UTF-8")));
                                break;
                            case "introduction":
                                ser.setIntroduction(item.getString("UTF-8"));
                                break;
                            case "status":
                                ser.setStatus(item.getString("UTF-8"));
                                break;
                        }
                    } else {
                        // 处理文件上传
                        if (!item.isFormField()) {
                            if (item.getInputStream().available() > 0) { // 确保文件流不为空
                                String fileName = item.getName();
                                if (fileName != null && !fileName.trim().isEmpty()) {
                                    fileName = fileName.substring(fileName.lastIndexOf(".")); // 获取文件扩展名
                                    fileName = "/" + new Date().getTime() + fileName; // 使用时间戳生成唯一文件名
                                    String path = this.getServletContext().getRealPath("/picture") + fileName;

                                    // 保存文件到服务器
                                    try (InputStream in = item.getInputStream();
                                         FileOutputStream out = new FileOutputStream(path)) {
                                        byte[] buffer = new byte[1024];
                                        int len;
                                        while ((len = in.read(buffer)) > 0) {
                                            out.write(buffer);
                                        }
                                    }
                                    // 设置 image 字段路径
                                    ser.setImage("/picture" + fileName);
                                    System.out.println("图片上传路径：" + ser.getImage());
                                }
                            }
                        }

                    }
                }
                // 调试：输出所有接收到的字段
                System.out.println("服务名称: " + ser.getName());
                System.out.println("服务分类: " + ser.getClassname());
                System.out.println("医生: " + ser.getDoctor());
                System.out.println("时长: " + ser.getTime() + " 分钟");
                System.out.println("价格: ￥" + ser.getPrice());
                System.out.println("简介: " + ser.getIntroduction());
                System.out.println("状态: " + ser.getStatus());
                System.out.println("图片路径: " + ser.getImage());
                // 插入数据到数据库
                gdao.insert(ser);// 重定向到加载服务列表的 Servlet
                // 插入成功后的控制台输出
                System.out.println("数据已成功插入到数据库！");
                // 重定向到服务管理页面
                response.sendRedirect("admin/servlet_manage.jsp");

            } catch (Exception e) {
                e.printStackTrace();
                request.setAttribute("message", "服务添加失败：" + e.getMessage());
                request.getRequestDispatcher("/admin/servlet_manage.jsp").forward(request, response);
            }
        }
    }

}